package com.liushunqiu.realtor.config;

import io.vertx.config.spi.ConfigStore;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;
@Slf4j
public class YamlConfigStore implements ConfigStore {

    /**
     * 默认端口
     */
    private final static int DEFAULT_PORT = 8080;

    private final Vertx vertx;
    private final String path;

    public YamlConfigStore(Vertx vertx, JsonObject configuration) {
        this.vertx = vertx;
        this.path = configuration.getString("path");
    }

    @Override
    public Future<Buffer> get() {
        Promise<Buffer> configPromise = Promise.promise();
        vertx.fileSystem().exists(path, existResultHandler -> {
            if (existResultHandler.succeeded() && existResultHandler.result()) {
                vertx.fileSystem()
                        .readFile(path)
                        .map(buffer -> {
                            Yaml yaml = new Yaml();
                            Map<String, Object> yamlConfig = yaml.load(buffer.toString());
                            return Buffer.buffer(new JsonObject(yamlConfig).encode());
                        }).onSuccess(configPromise::complete)
                        .onFailure(configPromise::fail);
            } else {
                log.error("当前项目缺少配置文件:{}", path, existResultHandler.cause());
                // 构建默认配置
                JsonObject defaultConfig = new JsonObject();
                JsonObject portConfig = new JsonObject();
                portConfig.put("port",DEFAULT_PORT);
                defaultConfig.put("server", portConfig);
                configPromise.complete(Buffer.buffer(defaultConfig.encode()));
            }
        });
        return configPromise.future();
    }
}
